package com.lianzai.common.executor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lianzai.camera.model.CameraBlackAndWhiteDO;
import com.lianzai.camera.model.CameraInfo;
import com.lianzai.camera.service.CameraService;
import com.lianzai.common.utils.R;
import com.lianzai.mobile.domain.CommunityInfoDO;
import com.lianzai.mobile.service.CommunityInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class LocalSvrSyncExecutor {

    public static void addCommunity(CommunityInfoDO community, CommunityInfoService communityService)
    {
        if (community.getLocalServerIp() == null || community.getLocalServerPort() < 1)
        {
            return;
        }

        new Thread(){
            public void run() {

                //更新同步状态为同步中
                community.setSyncStatus(CommunityInfoDO.SYNC_STATUS_RUNNING);
                communityService.updateSyncStatus(community);

                //同步到本地系统
                String url = "http://" + community.getLocalServerIp() + ":"
                        + community.getLocalServerPort() + "/remoteManage/addCommunity";

                try {
                    RestTemplate restTemplate = new RestTemplate();
                    R ret = restTemplate.postForObject(url, community, R.class);

                    //同步完成后更新同步状态
                    if ((int)ret.get("code") == 0) {
                        community.setSyncStatus(CommunityInfoDO.SYNC_STATUS_SUCCESS);
                    } else {
                        community.setSyncStatus(CommunityInfoDO.SYNC_STATUS_FAILED);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    community.setSyncStatus(CommunityInfoDO.SYNC_STATUS_FAILED);
                } finally {
                    communityService.updateSyncStatus(community);
                }

            }
        }.start();
    }

    public static void updateCommunity(CommunityInfoDO community, CommunityInfoService communityService) {
        if (community.getLocalServerIp() == null || community.getLocalServerPort() < 1)
        {
            return;
        }

        new Thread(){
            public void run() {

                //更新同步状态为同步中
                community.setSyncStatus(CommunityInfoDO.SYNC_STATUS_RUNNING);
                communityService.updateSyncStatus(community);

                //同步到本地系统
                String url = "http://" + community.getLocalServerIp() + ":"
                        + community.getLocalServerPort() + "/remoteManage/updateCommunity";

                try {
                    RestTemplate restTemplate = new RestTemplate();
                    R ret = restTemplate.postForObject(url, community, R.class);

                    //同步完成后更新同步状态
                    if ((int)ret.get("code") == 0) {
                        community.setSyncStatus(CommunityInfoDO.SYNC_STATUS_SUCCESS);
                    } else {
                        community.setSyncStatus(CommunityInfoDO.SYNC_STATUS_FAILED);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    community.setSyncStatus(CommunityInfoDO.SYNC_STATUS_FAILED);
                } finally {
                    communityService.updateSyncStatus(community);
                }
            }
        }.start();
    }

    public static void delCommunity(CommunityInfoDO community)
    {
        new Thread(){
            public void run() {
                JSONObject json = new JSONObject();
                json.put("id", community.getId());

                //同步到本地系统
                String url = "http://" + community.getLocalServerIp() + ":"
                        + community.getLocalServerPort() + "/remoteManage/delCommunity";

                RestTemplate restTemplate = new RestTemplate();
                restTemplate.postForObject( url, json, R.class);
            }
        }.start();
    }

    /**
     * 向本地服务器发放黑名单数据
     * @param blackCar
     * @param community
     */
    public static void addBlackListCar(CameraBlackAndWhiteDO blackCar,CommunityInfoDO community)
    {
        if (community.getLocalServerIp() == null || community.getLocalServerPort() < 1)
        {
            return;
        }
        new Thread(){
            public void run() {
                //同步到本地系统
                String url = "http://" + community.getLocalServerIp() + ":"
                        + community.getLocalServerPort() + "/remoteManage/addBlackListCar";

                RestTemplate restTemplate = new RestTemplate();
                restTemplate.postForObject( url, blackCar, R.class);
            }
        }.start();
    }

    /**
     * 向本地服务器修改了黑名单数据
     * @param blackCar
     * @param community
     */
    public static void modifyBlackListCar(CameraBlackAndWhiteDO blackCar,CommunityInfoDO community)
    {
        if (community.getLocalServerIp() == null || community.getLocalServerPort() < 1)
        {
            return;
        }
        new Thread(){
            public void run() {
                //同步到本地系统
                String url = "http://" + community.getLocalServerIp() + ":"
                        + community.getLocalServerPort() + "/remoteManage/modifyBlackListCar";
                RestTemplate restTemplate = new RestTemplate();
                restTemplate.postForObject( url, blackCar, R.class);
            }
        }.start();
    }

    /**
     * 删除了黑名单
     * @param blackCar
     * @param community
     */
    public static void delBlackListCar(CameraBlackAndWhiteDO blackCar,CommunityInfoDO community)
    {
        if (community.getLocalServerIp() == null || community.getLocalServerPort() < 1)
        {
            return;
        }
        new Thread(){
            public void run() {
                //同步到本地系统
                String url = "http://" + community.getLocalServerIp() + ":"
                        + community.getLocalServerPort() + "/remoteManage/delBlackListCar";
                RestTemplate restTemplate = new RestTemplate();
                restTemplate.postForObject( url, blackCar, R.class);
            }
        }.start();
    }

    /**
     * 向本地系统发送支付结果
     * @param orderId
     * @param payResult
     * @param community
     * @return
     */
    public static boolean informPayResultToLocalSystem(long orderId, long cameraId, int payResult, CommunityInfoDO community)
    {
        /*log.info("向本地系统发送开闸：orderId:{}, cameraId:{}, payResult:{}, community:{}",
                orderId, cameraId, payResult, community==null?"null" : JSON.toJSONString(community));*/
        if (community.getLocalServerIp() == null || community.getLocalServerPort() < 1)
        {
            return false;
        }

        //同步到本地系统
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("orderId", String.valueOf(orderId));
        result.put("cameraId", String.valueOf(cameraId));
        result.put("payResult", String.valueOf(payResult));
        String url = "http://" + community.getLocalServerIp() + ":"
                + community.getLocalServerPort() + "/remoteManage/payResult";
        RestTemplate restTemplate = new RestTemplate();
        R r = restTemplate.postForObject( url, result, R.class);

        if ((int)r.get("code") == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * 向本地系统发送停车券
     * @return
     */
    public static boolean addTicket(int ticketDuration, String carNumber, CommunityInfoDO community)
    {


        JSONObject json = new JSONObject();
        json.put("ticketDuration", ticketDuration);
        json.put("carNumber", carNumber);

        String url = "http://" + community.getLocalServerIp() + ":"
                + community.getLocalServerPort() + "/remoteManage/addTicket";
        RestTemplate restTemplate = new RestTemplate();
        R r = restTemplate.postForObject( url, json, R.class);

        if ((int)r.get("code") == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     *云端绑定小区规则的时候发起对本地的同步操作
     * 如果ruleId=-1是解绑 其余情况是绑定
     */

    public static void bindRuleOper(JSONObject ruleObject,CommunityInfoDO community)
    {
        if (community.getLocalServerIp() == null || community.getLocalServerPort() < 1)
        {
            return;
        }
        new Thread(){
            public void run() {
                //同步到本地系统
                String url = "http://" + community.getLocalServerIp() + ":"
                        + community.getLocalServerPort() + "/remoteManage/bindRule";
                RestTemplate restTemplate = new RestTemplate();

                //TODO 调用的远端接口无返回数据，此处的第三个参数应该修改，是否改为null待验证
                restTemplate.postForObject( url, ruleObject, JSONObject.class);

            }
        }.start();
    }


    /**
     * 如果修改了规则 则通知本地区下载 计费规则
     */
    public static void bindRuleWithLocalDownload(JSONObject ruleObject,CommunityInfoDO community)
    {
        if (community.getLocalServerIp() == null || community.getLocalServerPort() < 1)
        {
            return;
        }
        new Thread(){
            public void run() {
                //同步到本地系统
                String url = "http://" + community.getLocalServerIp() + ":"
                        + community.getLocalServerPort() + "/remoteManage/bindRuleWithLocalDownload";
                RestTemplate restTemplate = new RestTemplate();

                //TODO 调用的远端接口无返回数据，此处的第三个参数应该修改，是否改为null待验证
                restTemplate.postForObject( url, ruleObject, JSONObject.class);
            }
        }.start();
    }


    /**
     *云端通知本地小区开闸接口
     */
    public static R openGate(JSONObject cameraObject,CommunityInfoDO community)
    {
        if (community.getLocalServerIp() == null || community.getLocalServerPort() < 1)
        {
            return R.error(2,"小区没有绑定IP");
        }
        String url = "http://" + community.getLocalServerIp() + ":"
                + community.getLocalServerPort() + "/remoteManage/openGate";
        RestTemplate restTemplate = new RestTemplate();
        R retR = restTemplate.postForObject( url, cameraObject, R.class);
        return retR;
    }

    public static R openGateByCarNum(JSONObject cameraObject,CommunityInfoDO community)
    {
        if (community.getLocalServerIp() == null || community.getLocalServerPort() < 1)
        {
            return R.error(2,"小区没有绑定IP");
        }
        String url = "http://" + community.getLocalServerIp() + ":"
                + community.getLocalServerPort() + "/remoteManage/openGateByCarNum";
        RestTemplate restTemplate = new RestTemplate();
        R retR = restTemplate.postForObject( url, cameraObject, R.class);
        if(retR == null){
            return R.error();
        }
        return retR;
    }

    /**
     * 向本地系统新增相机配置
     * @param cameraInfo
     */
    public static void addCamera(CameraInfo cameraInfo, CommunityInfoDO community, CameraService cameraService)
    {
        if (community.getLocalServerIp() == null || community.getLocalServerPort() < 1)
        {
            return;
        }

        new Thread(){
            public void run() {

                //更新同步状态为同步中
                cameraInfo.setSyncStatus(CameraInfo.SYNC_STATUS_RUNNING);
                cameraService.updateSyncStatus(cameraInfo);

                //同步到本地系统
                String url = "http://" + community.getLocalServerIp() + ":"
                        + community.getLocalServerPort() + "/remoteManage/addCameraFromCloud";

                try {
                    RestTemplate restTemplate = new RestTemplate();
                    R ret = restTemplate.postForObject(url, cameraInfo, R.class);

                    //根据同步结果设置
                    if ((int)ret.get("code") == 0) {
                        cameraInfo.setSyncStatus(CameraInfo.SYNC_STATUS_SUCCESS);
                    } else {
                        cameraInfo.setSyncStatus(CameraInfo.SYNC_STATUS_FAILED);
                    }
                } catch (Exception e) {
                    cameraInfo.setSyncStatus(CameraInfo.SYNC_STATUS_FAILED);
                    e.printStackTrace();
                } finally {
                    //保存同步状态
                    cameraService.updateSyncStatus(cameraInfo);
                }
            }
        }.start();
    }

    /**
     * 向本地系统更新相机配置
     * @param cameraInfo
     */
    public static void updateCamera(CameraInfo cameraInfo, CommunityInfoDO community, CameraService cameraService)
    {
        if (community.getLocalServerIp() == null || community.getLocalServerPort() < 1)
        {
            return;
        }

        new Thread(){
            public void run() {

                //更新同步状态为同步中
                cameraInfo.setSyncStatus(CameraInfo.SYNC_STATUS_RUNNING);
                cameraService.updateSyncStatus(cameraInfo);

                //同步到本地系统
                String url = "http://" + community.getLocalServerIp() + ":"
                        + community.getLocalServerPort() + "/remoteManage/updateCamera";

                try {
                    RestTemplate restTemplate = new RestTemplate();
                    R ret = restTemplate.postForObject(url, cameraInfo, R.class);

                    //根据同步结果设置
                    if ((int)ret.get("code") == 0) {
                        cameraInfo.setSyncStatus(CameraInfo.SYNC_STATUS_SUCCESS);
                    } else {
                        cameraInfo.setSyncStatus(CameraInfo.SYNC_STATUS_FAILED);
                    }
                } catch (Exception e) {
                    cameraInfo.setSyncStatus(CameraInfo.SYNC_STATUS_FAILED);
                    e.printStackTrace();
                } finally {
                    cameraService.updateSyncStatus(cameraInfo);
                }
            }
        }.start();
    }

    /**
     * 向本地系统删除相机配置
     * @param cameraInfo
     */
    public static void delCamera(CameraInfo cameraInfo, CommunityInfoDO community)
    {
        if (community.getLocalServerIp() == null || community.getLocalServerPort() < 1)
        {
            return;
        }

        new Thread(){
            public void run() {
                //同步到本地系统
                String url = "http://" + community.getLocalServerIp() + ":"
                        + community.getLocalServerPort() + "/remoteManage/delCamera";

                RestTemplate restTemplate = new RestTemplate();
                restTemplate.postForObject(url, cameraInfo.getId(), R.class);
            }
        }.start();
    }

    public static void syncCameraToLocalSystem(CameraInfo cameraInfo, CommunityInfoDO community, CameraService cameraService) {
        if (community.getLocalServerIp() == null || community.getLocalServerPort() < 1)
        {
            return;
        }

        new Thread(){
            public void run() {

                //更新同步状态为同步中
                cameraInfo.setSyncStatus(CameraInfo.SYNC_STATUS_RUNNING);
                cameraService.updateSyncStatus(cameraInfo);

                //同步到本地系统
                String url = "http://" + community.getLocalServerIp() + ":"
                        + community.getLocalServerPort() + "/remoteManage/syncCamera";

                try {
                    RestTemplate restTemplate = new RestTemplate();
                    R ret = restTemplate.postForObject(url, cameraInfo, R.class);

                    //根据同步结果设置
                    if ((int)ret.get("code") == 0) {
                        cameraInfo.setSyncStatus(CameraInfo.SYNC_STATUS_SUCCESS);
                    } else {
                        cameraInfo.setSyncStatus(CameraInfo.SYNC_STATUS_FAILED);
                    }
                } catch (Exception e) {
                    cameraInfo.setSyncStatus(CameraInfo.SYNC_STATUS_FAILED);
                    e.printStackTrace();
                } finally {
                    //保存同步状态
                    cameraService.updateSyncStatus(cameraInfo);
                }
            }
        }.start();

    }
}
